/*eslint no-throw-literal: 0*/

class JJH5InteractionApp {
    constructor(){
        const userAgent=navigator.userAgent.toUpperCase();
        this.userAgent=userAgent;
        this.IS_ANDROID=userAgent.includes('ANDROID');
        this.IS_IOS=userAgent.includes('IPHONE OS');
        this.IS_HOST=true //userAgent.includes('JJWEBVIEW');
        this.RESULT={};
    }

    /**
     * 执行H5与App交换的方法
     * @method call
     * @for JJH5InteractionApp
     * @param {string} functionName 需要执行的方法
     * @param {object} param 需要与App交互的参数
     * @param {function} successCallBack 成功的回调
     * @param {function} errorCallBack 失败的回调
     */
    call=(functionName='',param={},successCallBack=null,errorCallBack=null)=>{
        let functionID=Math.ceil(Math.random() * new Date().getTime())+new Date().getTime();
        this.RESULT=Object.assign({},this.RESULT,{[functionID]:{}})
        if(this.IS_ANDROID && this.IS_HOST){
            this.addiframe(functionName,param,functionID,'JJApp.callSuccess','JJApp.callError')
        }else if(this.IS_IOS && this.IS_HOST){
            this.addiframe(functionName,param,functionID,'JJApp.callSuccess','JJApp.callError')
        }
        if(successCallBack!==null||errorCallBack!==null){
            Object.defineProperty(this.RESULT,functionID,{
                configurable: true,//是否可以删除目标属性
                set:(v)=>{
                    let {isSuccess='success',data} = v;
                    if(isSuccess==='success'){
                        this.detectionType(successCallBack)==='Function'&&successCallBack(data);
                    }else if (isSuccess==='fail') {
                        this.detectionType(successCallBack)==='Function'&&errorCallBack(data);
                    }
                }
            })
        }
    }
    //成功回调
    callSuccess=(response)=>{
        try {
            if(Object.prototype.toString.call(response)==='[object String]'){
                let dataParse=JSON.parse(response);
                let {functionID=null,data} = dataParse;
                if(functionID==null||functionID===''){
                    throw '返回数据functionID字段不可为null or 空';
                }
                this.RESULT[functionID]=this.dataConversion(data,'success');

            }else{
                throw `数据返回格式有误,应为：Json,现状：${this.detectionType(response)}`;
            }
        }catch (e) {
            throw e;
        }
    }
    //失败回调
    callError=(response)=>{
        try {
            if(Object.prototype.toString.call(response)==='[object String]'){
                let dataParse=JSON.parse(response);
                let {functionID=null,data} = dataParse;
                if(functionID==null||functionID===''){
                    throw '返回数据functionID字段不可为null or 空';
                }
                this.RESULT[functionID]=this.dataConversion(data,'fail');
            }else{
                throw `数据返回格式有误,应为：Json,现状：${this.detectionType(response)}`;
            }
        }catch (e) {
            throw e;
        }
    }
    //创建iframe
    addiframe=(functionName='',param={},functionID=null,successCallBackName=null,errorCallBackName=null)=>{
        if(functionID==null||functionID===''){
            throw 'functionID字段不可为null or 空';
        }
        if(param==null){
            param={};
        }
        let params=Object.assign({},{data:param},{
            functionID:functionID,
            successCallBackName:successCallBackName,
            errorCallBackName:errorCallBackName,
        })
        let _iframe=document.createElement('iframe');
            _iframe.src=`jjnative://${functionName}?param=${encodeURIComponent(JSON.stringify(params))}`;
            _iframe.style.display='none';
        document.body.appendChild(_iframe);
        setTimeout(()=>_iframe.parentNode.removeChild(_iframe),30000);
    }

    dataConversion=(response,isSuccess)=>{
        switch (this.detectionType(response)) {
            case 'Null':{
                return {isSuccess:isSuccess,data:''}
            }
            default:{
                return {isSuccess:isSuccess,data:response}
            }
        }
    }

    detectionType=(response)=>{
        return Object.prototype.toString.call(response).replace(/^\[object\s/,'').replace(/\]/,'');
    }
}
window.JJApp=new JJH5InteractionApp();
export default window.JJApp;
